package utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;

import java.util.Date;

@ConfigurationProperties("jwt.config")
@Data
public class JwtUtils {
    private String key;
    private Long ttl;
    //1.生成token
    public String getToken(String id, String subject, String roles){
        System.out.println("key  =>  "+key);
        JwtBuilder jwtBuilder = Jwts.builder().setId(id)
                .setSubject(subject)
                .setIssuedAt(new Date())
                .signWith(SignatureAlgorithm.HS256, "zelin")
                .claim("roles", roles);
        if (ttl>0){
            jwtBuilder.setExpiration(new Date(System.currentTimeMillis()+ttl));
        }
        return jwtBuilder.compact();
    }
    //2.解析token
    public Claims getClaims(String token){
        return Jwts.parser().setSigningKey("zelin").parseClaimsJws(token).getBody();
    }
}
